// 代码编辑器实现
class CodeEditor 
{
    constructor(textareaId) 
    {
        this.textarea = document.getElementById(textareaId);
        this.editorContainer = document.createElement('div');
        this.lineNumbers = document.createElement('div');
        this.highlight = document.createElement('div');
        this.curLanguage = document.getElementById("language-selector").querySelector("option[selected]").value;
        this.codeMap = {};
        this.bracketMap = {
            '(': { pair: '()' },
            '[': { pair: '[]' },
            '{': { pair: '{}' },
            "'": { pair: "''" },
            '"': { pair: '""' }
        };
        
        this.setupEditor();
        this.setupEventListeners();
    }
    
    setupEditor() 
    {
        // 创建编辑器容器
        this.editorContainer.className = 'editor-container';
        this.textarea.parentNode.insertBefore(this.editorContainer, this.textarea);
        this.editorContainer.appendChild(this.textarea);
        
        // 创建行号
        this.lineNumbers.className = 'editor-line-numbers';
        this.editorContainer.appendChild(this.lineNumbers);
        
        // 创建代码高亮层
        this.highlight.className = 'editor-highlight';
        this.editorContainer.appendChild(this.highlight);
        
        // 设置初始样式
        this.update();
        this.setupCodeStorge();
    }
    
    setupEventListeners() 
    {
        // 滚动同步
        this.editorContainer.addEventListener('scroll', () => {
            this.syncScrollPositions();
        });

        // 文本变化事件
        this.textarea.addEventListener('input', () => {
            this.update();
        });
        
        // 键盘事件处理
        this.textarea.addEventListener('keydown', (e) => {
            const config = this.bracketMap[e.key];
            if (e.key === 'Tab') 
            {
                e.preventDefault();
                this.insertText('    ');
            }
            else if (e.key === 'Enter') 
            {
                const currentLine = this.getCurrentLine();
                const indent = currentLine.match(/^\s*/)[0];
                setTimeout(() => { this.insertText(indent); }, 0);
            }
            else if (config !== undefined)
            {
                e.preventDefault();
                const start = this.textarea.selectionStart;
                const end = this.textarea.selectionEnd;
                this.textarea.value = this.textarea.value.slice(0, start) + config.pair[0] + config.pair[1] + this.textarea.value.slice(end);
                this.textarea.selectionStart = this.textarea.selectionEnd = start + 1;
            }
            requestAnimationFrame(() => {
                this.highlight.scrollLeft = this.textarea.scrollLeft;
            });
        });

        // 实现分割条拖动功能
        const resizeHandle = document.getElementById('resize-handle');
        const leftPanel = document.getElementById('problem-description-container');
        const rightPanel = document.querySelector('.coding-container');
        
        let isResizing = false;
        
        resizeHandle.addEventListener('mousedown', function(e) {
            isResizing = true;
            resizeHandle.classList.add('dragging');
            document.body.style.cursor = 'col-resize';
            document.body.style.userSelect = 'none';
            
            // 防止文本选择
            e.preventDefault();
        });
        
        document.addEventListener('mousemove', function(e) {
            if (!isResizing) return;
            
            const containerRect = document.querySelector('.leetcode-layout').getBoundingClientRect();
            const percent = (e.clientX - containerRect.left) / containerRect.width * 100;
            
            // 限制分割条移动范围（10% - 90%）
            const leftPercent = Math.max(20, Math.min(80, percent));
            
            leftPanel.style.width = leftPercent + '%';
            rightPanel.style.width = (100 - leftPercent) + '%';
        });
        
        document.addEventListener('mouseup', function() {
            isResizing = false;
            resizeHandle.classList.remove('dragging');
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
        });
    }

    syncScrollPositions() 
    {
        const container = this.editorContainer;
        const scrollTop = container.scrollTop;
        const scrollLeft = container.scrollLeft;

        // 垂直同步所有元素
        this.textarea.scrollTop = scrollTop;
        this.lineNumbers.scrollTop = scrollTop;
        this.highlight.scrollTop = scrollTop;

        // 水平同步代码基底和高亮
        this.textarea.scrollLeft = scrollLeft;
        this.highlight.scrollLeft = scrollLeft;

        // 行号区域保持水平位置0
        this.lineNumbers.scrollLeft = 0;
    }

    setupCodeStorge()
    {
        let options = document.getElementById("language-selector").children;
        for (const option of options)
        {
            this.codeMap[option.value] = "";
        }
    }
    
    getCurrentLine() 
    {
        const startPos = this.textarea.selectionStart;
        const value = this.textarea.value;
        let lineStart = value.lastIndexOf('\n', startPos - 1) + 1;
        let lineEnd = value.indexOf('\n', startPos);
        if (lineEnd === -1) lineEnd = value.length;
        return value.substring(lineStart, lineEnd);
    }
    
    insertText(text) 
    {
        const start = this.textarea.selectionStart;
        const end = this.textarea.selectionEnd;
        const value = this.textarea.value;
        
        this.textarea.value = value.substring(0, start) + text + value.substring(end);
        this.textarea.selectionStart = this.textarea.selectionEnd = start + text.length;
        
        this.update();
    }

    update()
    {
        const lines = this.textarea.value.split('\n');
        this.lineNumbers.innerHTML = lines.map((_, i) => i + 1).join('<br>');
        this.textarea.style.height = `${this.lineNumbers.scrollHeight}px`;
        this.editorContainer.style.height = this.textarea.style.height;
        if (typeof hljs !== 'undefined') 
        {
            this.highlight.innerHTML = hljs.highlightAuto(this.textarea.value).value;
            this.highlight.innerHTML += this.textarea.value.endsWith('\n') ? ' ' : '';
            this.highlight.scrollLeft = this.textarea.scrollLeft;
        }
    }
    
    getValue() 
    {
        return this.textarea.value;
    }
    
    setValue(newLanguage) 
    {
        if (this.curLanguage !== newLanguage)
        {
            this.codeMap[this.curLanguage] = this.textarea.value;
            this.textarea.value = this.codeMap[newLanguage];
            this.curLanguage = newLanguage;
            this.update();
        }
    }

    resetValue()
    {
        this.codeMap[this.curLanguage] = "";
        this.textarea.value = "";
        this.update();
    }
}

function setActiveBtn(case_btn)
{
    case_btn.classList.add("active");
    document.getElementById(case_btn.getAttribute('data-tab')).classList.add("active");
}

// 获取页面数据
async function getData()
{
    const queryParams = new URLSearchParams(window.location.search);
    let name = queryParams.get("name");
    const data = await fetch(`/problems/problem/data.json?name=${encodeURIComponent(name)}`, {
        method: "GET", 
        headers: 
        {
            "Content-Type": "application/json"
        },
    })
    if (data.ok === false)
    {
        window.location.href = "/problems/404.html";
    }
    return data.json();
}

function stopPropagation(e) 
{
    e = e || window.event;
    if (e.stopPropagation) 
    {
        e.stopPropagation();
    } 
    else 
    {
        e.cancelBubble = true;
    }
}

function getArg(method, raw_data, type, output)
{
    if (removeFormat(raw_data, type) != "")
    {
        switch (method)
        {
        case "length":
            output.push(JSON.parse(raw_data).length);
        }
    }
    return -1;
}

function formatResult(str, type)
{
    switch (type)
    {
    case "str":
        return `"${str}"`;
    case "int_array":
        str = str.replaceAll(' ', `,`);
        return `[${str}]`;
    case "str_array":
        str = str.replaceAll(' ', `","`);
        return `["${str}"]`;
    default:
        return str;
    }
}

function removeFormat(str, test_type)
{
    if (test_type == "str_array")
    {
        if (!str.includes("\",\"") || (str[1] != '\"' || str[str.length - 2] != '\"'))
        {
            return "";
        }
        str = str.replaceAll("\",\"", ' ');
        if (str[0] != '[' && str[str.length - 1] != ']')
        {
            return "";
        }
        str = str.slice(2, str.length - 2);
        if (str == "")
        {
            return "";
        }
    }
    else if (test_type == "int_array")
    {
        if (!/^[0-9,]+$/.test(str.slice(1, str.length - 1)))
        {
            return "";
        }
        str = str.replaceAll(',', ' ');
        if (str[0] != '[' && str[str.length - 1] != ']')
        {
            return "";
        }
        str = str.slice(1, str.length - 1);
        if (str == "")
        {
            return "";
        }
    }
    else if (test_type == "str")
    {
        if (str[0] != '\"' && str[str.length - 1] != '\"')
        {
            return "";
        }
        str = str.slice(1, str.length - 1);
        if (str == "")
        {
            return "";
        }
    }
    else if (test_type == "int")
    {
        if (!/^[0-9]+$/.test(str))
        {
            return "";
        }
        if (str == "")
        {
            return "";
        }
    }
    return str;
}

// 测试结果渲染
async function renderTestResult(response, type, output_map)
{
    const content = await response.json();
    const display_arr = document.getElementsByClassName("display");
    const case_btns = document.getElementsByClassName("case-btn");
    console.log(content);
    console.log(output_map);
    for (let i = 0; i < display_arr.length; ++i)
    {
        display_arr.item(i).textContent = "";
    }
    switch (content.status)
    {
    case "check":
        for (let i = 0, j = 0; i < display_arr.length; ++i)
        {
            if (output_map.has(i))
            {
                switch (output_map.get(i))
                {
                case "fmterr":
                    display_arr.item(i).textContent = "format error";
                    break;
                default:
                    break;
                }
            }
            else
            {
                display_arr.item(i).textContent = formatResult(content.results[j], type);
                ++j;
            }
        }
        break;
    case "runerr":
        for (let i = 0, j = 0; i < display_arr.length; ++i)
        {
            if (output_map.has(i))
            {
                switch (output_map.get(i))
                {
                case "fmterr":
                    display_arr.item(i).textContent = "format error";
                    break;
                default:
                    break;
                }
            }
            else
            {
                if (j == content.results.length - 1)
                {
                    display_arr.item(i).textContent = `runtime error: ${content.msg}`;
                    display_arr.item(i).textContent += formatResult(content.results[j], type);;
                    case_btns.item(i).click();
                }
                else
                {
                    display_arr.item(i).textContent = formatResult(content.results[j], type);
                    ++j;
                }
            }
        }
        break;
    case "comerr":
        for (let i = 0, flag = false; i < display_arr.length; ++i)
        {
            if (output_map.has(i))
            {
                switch (output_map.get(i))
                {
                case "fmterr":
                    display_arr.item(i).textContent = "format error";
                    break;
                default:
                    break;
                }
            }
            else if (flag == false)
            {
                display_arr.item(i).textContent = `complie error: ${content.msg}`;
                case_btns.item(i).click();
                flag = true;
            }
        }
        break;
    }
}

// 渲染题目信息
function renderInfo(content, codeEditor)
{
    let parent = document.querySelector(".problem-description-container");
    let element = parent.querySelector(".problem-header");
    let fragment = new DocumentFragment();

    // 渲染基础信息
    let header = document.createElement("h2");
    header.setAttribute("class", "problem-title");
    header.textContent = content.name;
    fragment.appendChild(header);

    let div = document.createElement("div");
    div.setAttribute("class", "problem-meta");
    let span = document.createElement("span");
    switch (content.difficulty)
    {
    case "简单":
        span.setAttribute("class", "badge easy");
        break;
    case "中等":
        span.setAttribute("class", "badge medium");
        break;
    case "困难":
        span.setAttribute("class", "badge hard");
        break;
    }
    span.textContent = content.difficulty;
    div.append(span);
    for (const tag of content.tags)
    {
        span = document.createElement("span");
        span.setAttribute("class", "problem-tag");
        span.textContent = tag;
        div.append(span);
    }
    fragment.appendChild(div);
    element.appendChild(fragment);

    // 渲染题目描述
    parent = parent.querySelector(".problem-content");
    element = document.getElementById("description");
    element = element.querySelector(".content-text");
    let p;
    for (let para of content.description)
    {
        p = document.createElement("p");
        p.innerHTML = para;
        fragment.appendChild(p);
    }
    let count = 1;
    let pre;
    for (let example of content.examples)
    {
        div = document.createElement("div");
        div.setAttribute("class", "sample");
        h = document.createElement("h3");
        h.textContent = `示例 ${count}:`;
        div.appendChild(h);
        pre = document.createElement("pre");
        pre.textContent = example;
        div.appendChild(pre);
        fragment.appendChild(div);
        ++count;
    }
    div = document.createElement("div");
    div.setAttribute("class", "constraints");
    h = document.createElement("h3");
    h.textContent = `提示:`;
    div.appendChild(h);
    let ul = document.createElement("ul");
    let li;
    for (const hint of content.hints)
    {
        li = document.createElement("li");
        li.innerHTML = hint;
        ul.appendChild(li);
    }
    div.appendChild(ul);
    fragment.appendChild(div);
    element.appendChild(fragment);

    // 渲染测试用例
    element = document.getElementById("examples");
    let case_btns_arr = document.createElement("div");
    case_btns_arr.setAttribute("class", "case-btns");
    let add_btn = document.createElement("button");
    add_btn.setAttribute("class", "case-tag-btn");
    add_btn.setAttribute("id", "add-btn");
    add_btn.textContent = "+";
    let sub_btn = document.createElement("button");
    sub_btn.setAttribute("class", "case-tag-btn");
    sub_btn.setAttribute("id", "test-sub-btn");
    sub_btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="icon" version="1.1" viewBox="0 0 100 100">
<polygon points="0, 100 0, 0 100, 50" fill="#696969"></polygon></svg>`;
    case_btns_arr.appendChild(add_btn);
    case_btns_arr.appendChild(sub_btn);
    let case_contents_arr = document.createElement("div");
    case_contents_arr.setAttribute("class", "case-contents");
    element.appendChild(case_btns_arr);
    element.appendChild(case_contents_arr);
    let close_btn = document.createElement("button");
    close_btn.setAttribute("class", "close-btn");
    close_btn.textContent = "x";
    close_btn.addEventListener('click', function(e) 
    {
        let parent = this.parentElement;
        let tem = parent.classList.contains("active");
        document.getElementById(parent.getAttribute('data-tab')).remove();
        parent.removeChild(this);
        parent.remove();
        let case_btns = case_btns_arr.querySelectorAll(".case-btn");
        let count = case_btns.length;
        if (count > 0)
        {
            case_btns_arr.children[count - 1].appendChild(this);
            if (add_btn.style.display == "none")
            {
                add_btn.style.display = "inline-flex";
            }
        }
        if (tem && count > 0)
        {
            setActiveBtn(case_btns[0]);
        }
        stopPropagation(e);
    });
    let test_tags = new Array(), test_types = new Array(), map = new Map();
    content.test.types.forEach(type => {
        test_types.push(type);
    });
    content.test.values[0].forEach(tag => {
        test_tags.push(tag.split(" ")[0]);
    });
    content.test.methods.forEach(method => {
        map.set(method.index, method.handle);
    });
    add_btn = document.getElementById("add-btn");
    add_btn.addEventListener("click", function() 
    {
        let case_btns = case_btns_arr.querySelectorAll(".case-btn");
        let count = case_btns.length;
        if (count == 7)
        {
            this.style.display = "none";
        }
        let case_btn = document.createElement("button");
        case_btn.classList.add("case-tag-btn", "case-btn");
        case_btn.setAttribute("data-tab", "case " + (count + 1));
        case_btn.textContent = "case " + (count + 1);
        let tab_div = document.createElement("div");
        tab_div.setAttribute("class", "case-tag-panel");
        tab_div.setAttribute("id", "case " + (count + 1));
        let div = document.createElement("div");
        div.setAttribute("class", "content-text");
        let tag, input_box;
        for (let i = 0; i < test_tags.length; ++i)
        {
            tag = document.createElement("label")
            tag.setAttribute("class", "label-text");
            tag.setAttribute("for", test_tags[i] + '-' + (count + 1));
            tag.textContent = test_tags[i];
            input_box = document.createElement("input");
            input_box.setAttribute("id", test_tags[i] + '-' + (count + 1));
            div.appendChild(tag);
            div.appendChild(input_box);
        }
        tag = document.createElement("span");
        tag.setAttribute("class", "label-text");
        tag.textContent = "输出";
        input_box = document.createElement("div");
        input_box.setAttribute("class", "display");
        div.appendChild(tag);
        div.appendChild(input_box);
        tab_div.appendChild(div);
        case_contents_arr.appendChild(tab_div);
        if (count > 0)
        {
            close_btn = case_btns[count - 1].removeChild(case_btns[count - 1].querySelector(".close-btn"));
        }
        else
        {
            setActiveBtn(case_btn);
        }
        case_btn.appendChild(close_btn);
        case_btn.addEventListener('click', function() 
        {
            const case_btns = case_btns_arr.querySelectorAll(".case-btn");
            const case_panels = case_contents_arr.querySelectorAll(".case-tag-panel");
            case_btns.forEach(btn => btn.classList.remove('active'));
            case_panels.forEach(panel => panel.classList.remove('active'));
            this.classList.add('active');
            document.getElementById(this.getAttribute('data-tab')).classList.add('active');
        });
        case_btns_arr.insertBefore(case_btn, add_btn);
    });
    content.test.values.forEach(case_content => {
        add_btn.click();
        let index = case_contents_arr.childElementCount - 1;
        for (let i = 0; i < case_content.length; ++i)
        {
            let input = case_content[i].split(' ');
            let ele_id = input[0] + '-' + (index + 1);
            let element = document.getElementById(ele_id);
            if (test_types[i].includes("array"))
            {
                element.value = '[' + input[1] + ']';
            }
            else
            {
                element.value = input[1];
            }
        }
    });
    document.getElementById("test-sub-btn").addEventListener('click', function() 
    {
        if (codeEditor.curLanguage !== "cpp")
        {
            alert("no support");
            return;
        }
        let request = new Object(), output_map = new Map(), is_format_error = false, no_content = 1, count = 0;
        const queryParams = new URLSearchParams(window.location.search);
        request.name = queryParams.get("name");
        request.code = codeEditor.getValue();
        request.mode = "test";
        request.language = codeEditor.curLanguage;
        request.examples = new Array();
        request.args = new Array();
        case_contents_arr.querySelectorAll(".case-tag-panel").forEach(text => {
            let inputs = text.querySelector(".content-text").getElementsByTagName("input"), example = "", tem = Array();
            for (let i = 0, str = ""; i < inputs.length; ++i)
            {
                str = inputs.item(i).value;
                if (str == "")
                {
                    no_content *= 1;
                }
                else
                {
                    no_content *= 0;
                    if (map.has(i))
                    {
                        getArg(map.get(i), str, test_types[i], tem);
                    }
                    str = removeFormat(str, test_types[i]);
                    if (str == "")
                    {
                        is_format_error = true;
                        output_map.set(count, "fmterr");
                        break;
                    }  
                    example += str;
                    example += "\n";
                }
            }
            if (no_content == 1)
            {
                output_map.set(count, "empty");
            }
            else if (!is_format_error)
            {
                request.args.push(tem);
                request.examples.push(example);
            }
            is_format_error = false, no_content = 1, ++count;
        });
        fetch("/submit", 
        {
            method: "POST",
            headers:
            {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(request)
        })
        .then(response => {
            renderTestResult(response, test_types[test_types.length - 1], output_map);
        })
    });

    // 渲染题解
    element = document.getElementById("solutions");
    element = element.querySelector(".content-text");
    for (const solution of content.solutions)
    {
        h = document.createElement("h3");
        h.textContent = solution.title;
        fragment.appendChild(h);
        p = document.createElement("p");
        p.innerHTML = solution.description;
        fragment.appendChild(p);
        pre = document.createElement("pre");
        let code = document.createElement("code");
        code.className = 'language-cpp';
        code.textContent = solution.code;
        hljs.highlightElement(code);
        pre.appendChild(code);
        fragment.appendChild(pre);
        p = document.createElement("p");
        p.innerHTML = "<strong>复杂度分析：</strong>";
        fragment.appendChild(p);
        ul = document.createElement("ul");
        li = document.createElement("li");
        li.innerHTML = solution.complexity.time;
        ul.appendChild(li);
        li = document.createElement("li");
        li.innerHTML = solution.complexity.space;
        ul.appendChild(li);
        fragment.append(ul);
    }
    element.appendChild(fragment);
}

async function initInfo(codeEditor)
{
    const content = await getData();
    renderInfo(content, codeEditor);
    return content.test;
}

// 提交结果渲染
async function renderResult(response, type_tag_promise)
{
    let content = await response.json();
    let type_and_tag_arr = await type_tag_promise;
    let resultNode = document.getElementById("submissions");
    let result = resultNode.querySelector(".content-text .submission-list");
    let fragment = new DocumentFragment(), node;
    let test_tags = new Array(), test_types = new Array();
    test_types = type_and_tag_arr.types;
    test_types.pop();
    type_and_tag_arr.values[0].forEach(tag => {
        test_tags.push(tag.split(" ")[0]);
    });
    result.textContent = "";
    switch (content.status)
    {
    case "comerr":
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "状态: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = "complie error";
        fragment.appendChild(node);
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "消息: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = content.msg;
        fragment.appendChild(node);
        break;
    case "runerr":
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "状态: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = "runtime error";
        fragment.appendChild(node);
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "消息: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = content.msg;
        fragment.appendChild(node);
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "错误用例: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        for (let i = 0, examples = content.which.split('\n'), char = '\n'; i < examples.length; ++i)
        {
            if (i == examples.length - 1)
            {
                char = '';
            }
            node.textContent += `${test_tags[i]}: ${formatResult(examples[i], test_types[i])}${char}`;
        }
        fragment.appendChild(node);
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "输出: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = content.result;
        fragment.appendChild(node);
        break;
    case "wrong":
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "状态: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = "wrong";
        fragment.appendChild(node);
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "错误用例: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        console.log(content.which);
        for (let i = 0, examples = content.which.split('\n'), char = '\n'; i < examples.length - 1; ++i)
        {
            if (i == examples.length - 2)
            {
                char = '';
            }
            node.textContent += `${test_tags[i]}: ${formatResult(examples[i], test_types[i])}${char}`;
        }
        fragment.appendChild(node);
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "输出: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = content.result;
        fragment.appendChild(node);
        break;
    case "correct":
        node = document.createElement("span");
        node.setAttribute("class", "label-text");
        node.textContent = "状态: ";
        fragment.appendChild(node);
        node = document.createElement("div");
        node.setAttribute("class", "display");
        node.textContent = "result correct";
        fragment.appendChild(node);
        break;
    }
    result.appendChild(fragment);
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanels = document.querySelectorAll('.tab-panel');
    tabButtons.forEach(btn => btn.classList.remove('active'));
    tabPanels.forEach(panel => panel.classList.remove('active'));
    document.getElementById("submissions-btn").classList.add('active');
    document.getElementById("submissions").classList.add('active');
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() 
{
    // 初始化代码编辑器
    const codeEditor = new CodeEditor('code-editor');

    // 初始化标签页
    const type_tag_promise = initInfo(codeEditor);
    
    // 语言选择切换
    document.getElementById('language-selector').addEventListener('change', function() 
    {
        if (this.value !== "cpp")
        {
            alert("no support");
        }
        codeEditor.setValue(this.value);
    });
    
    // 初始化代码高亮
    if (typeof hljs !== 'undefined') 
    {
        hljs.highlightAll();
    }

    // 标签页切换
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanels = document.querySelectorAll('.tab-panel');
    tabButtons.forEach(button => {
        button.addEventListener('click', function() 
        {
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabPanels.forEach(panel => panel.classList.remove('active'));
            this.classList.add('active');
            const tabId = this.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');
        });
    });

    // 重置代码按钮
    document.getElementById('reset-btn').addEventListener('click', function() 
    {
        codeEditor.resetValue();
    });

    // 提交代码按钮
    document.getElementById("result-sub-btn").addEventListener('click', function() 
    {
        if (codeEditor.curLanguage !== "cpp")
        {
            alert("no support");
            return;
        }
        let content = {};
        const queryParams = new URLSearchParams(window.location.search);
        content.name = queryParams.get("name");
        content.code = codeEditor.getValue();
        content.mode = "formal";
        content.language = codeEditor.curLanguage;
        fetch("/submit", 
        {
            method: "POST", 
            headers: 
            {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(content)
        })
        .then(response => {
            renderResult(response, type_tag_promise);
        })
    });
});